
const vss_s = `
  // 声明 attribute 变量，此变量必须是全局的
  attribute vec4 a_Position;
  // 定义定点着色器的main函数
  void main() {
    // 为 定点着色器的属性 gl_Position 赋值
    gl_Position = a_Position;
    // 为 定点着色器的属性 gl_PointSize 赋值
    gl_PointSize = 10.0;
  }
`;

const fs_s = `
  // 定义 片元着色器 的 main 函数
  void main() {
    // 为 片元着色器 的 唯一属性 gl_FragColor 赋值
    gl_FragColor = vec4(1, 0, 0, 1);
  }
`

function main() {
  const canvas = document.getElementById('webgl');
  if (!canvas) {
    alert('Field for got canvas by id');
    return false;
  }
  const gl = canvas.getContext('webgl');
  if (!gl) {
    alert('Field for got webgl');
    return false;
  }
  if (!initShaders(gl, vss_s, fs_s)) {
    alert('Field for init shaders');
    return false;
  }

  const a_Position = gl.getAttribLocation(gl.program, 'a_Position');

  canvas.onmousedown = function (event) {
    click(event, gl, canvas, a_Position);
  }
  gl.clearColor(0, 0, 0, 1);
  gl.clear(gl.COLOR_BUFFER_BIT);
}
var g_points = [];
function click(event, gl, canvas, a_Position) {
  const clientX = event.clientX;
  const clientY = event.clientY;
  const rect = event.target.getBoundingClientRect();
  const x = ((clientX - rect.left) - canvas.width * 0.5) / (canvas.width * 0.5);
  const y = (canvas.height * 0.5 - (clientY - rect.top)) / (canvas.height * 0.5);
  g_points.push({'x': x, 'y': y});
  gl.clearColor(0, 0, 0, 1);
  gl.clear(gl.COLOR_BUFFER_BIT);
  for (let index = 0; index < g_points.length; index++) {
    const point = g_points[index];
    const x = point['x'];
    const y = point['y'];
    gl.vertexAttrib3f(a_Position, x, y, 0);
    gl.drawArrays(gl.program, 0, 1);
  }
}